package com.xxxy.jsq.action.role;

import com.xxxy.jsq.dao.RoleDao;
import com.xxxy.jsq.model.Role;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/addRoleServlet")
public class addRoleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public addRoleServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码，避免中文乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 创建角色DAO对象
        RoleDao dao = new RoleDao();

        // 创建角色模型对象
        Role model = new Role();

        // 获取页面传递的参数（与前端表单字段名保持一致）
        String roleName = request.getParameter("cname");   // 角色名称
        String roleFlag = request.getParameter("cflag");   // 状态

        // 设置模型对象属性
        if (roleName != null && !roleName.equals("")) {
            model.setRoleName(roleName);
        }
        if (roleFlag != null && !roleFlag.equals("")) {
            model.setRoleFlag(roleFlag);
        }

        // 调用DAO层的添加方法
        String result = dao.add(model);

        // 返回处理结果给前端
        PrintWriter out = response.getWriter();
        out.print(result);  // 返回"Ok"表示成功，"Same"表示名称重复，"Err"表示失败
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // POST请求也交给doGet处理
        doGet(request, response);
    }
}